<template>
  <div>

    <div class="app_card mb-2 pt-4 pb-4">
      <div class="d-flex justify-content-end align-items-center">
        <div>
          <el-button type="primary" plain @click="expandAll()"><el-icon>
              <ArrowUp />
            </el-icon>全部展开</el-button>
          <el-button type="primary" plain @click="collapseAll()"><el-icon>
              <ArrowDown />
            </el-icon>全部收回</el-button>
          <el-button type="primary" @click="onAdd()">添加</el-button>
        </div>
      </div>
    </div>

    <div class="app_card pt-4  pb-5">
      <!-- <el-table stripe :data="dataOfTable" height="calc(100vh - 300px)" sortable="custom" row-key="title" default-expand-all size="small"> -->
      <el-table stripe :data="dataOfTable" height="calc(100vh - 300px)" sortable="custom" default-expand-all size="small"
        row-key="id" lazy ref="theTableRef" default-expand-all:true
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">

        <el-table-column prop="id" label="ID" sortable fixed align="center" width="200"> </el-table-column>
        <el-table-column prop="label" label="名称" sortable align="center"> </el-table-column>
        <el-table-column prop="Rtype" label="类型" sortable align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.Rtype == 2" type="danger" disable-transitions>按钮</el-tag>
            <el-tag v-if="scope.row.Rtype == 1" type="success" disable-transitions>菜单</el-tag>
            <el-tag v-if="scope.row.Rtype == 0" disable-transitions>区域</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" sortable align="center"> </el-table-column>
        <el-table-column prop="FileName" label="文件名" sortable align="center">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="onEditRow(scope.row)">编辑</el-button>
            <!-- <el-button link type="primary" @click="onDeleteRow(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <edit-dialog ref="editDialogRef" @success="loadData()"></edit-dialog>
  </div>
</template>
    
<script setup>
/**
* 菜单管理列表组件
*/
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import EditDialog from './EditDialog.vue';
import useAuthStore from '@/stores/useAuthStore';
import { getNewObj } from '@/utils/EsCommon';

// ======================================================
//                      变量声明
// ======================================================

const authStore = useAuthStore();
// 组件引用
const theTableRef = ref(null);
const editDialogRef = ref(null);
// 表格数据
const dataOfTable = ref([]);
const treeOption = ref([]);
// 表格数据
const list = ref([]);
// 表格查询参数
const queryForm = ref({
  page: 1,
})
// 表格查询参数
const queryParam = ref({
  sort: "id",
  order: "desc",
  limit: 10,
  query: "",
})

// ======================================================
//                      点击操作
// ======================================================

// 点击刷新按钮
const onRefresh = () => {
  loadData();
}

// 点击新增按钮
const onAdd = () => {

  editDialogRef.value.show("添加", null, treeOption.value);
}

// 点击快速搜索按钮
const onSearch = (param) => {
  loadData();
}

// 点击行内编辑按钮
const onEditRow = (row) => {
  editDialogRef.value.show("编辑 ", row, treeOption.value);
}

// 点击行内删除按钮
const onDeleteRow = (row) => {
  ElMessageBox.confirm("确定要删除该记录吗？", "警告").then(() => {
    // EsAjax.delete(ApiUrls.articleCategoryDelete, { params: { id: row.id } })
    //   .then(res => {
    //     if (res.data.code != 200) {
    //       ElMessage.warning(res.data.data + res.data.msg);
    //       return;
    //     }
    //     loadData();
    //   })
    //   .catch(err => { ElMessage.error("网络错误：", err.message) });
  }).catch(() => { });
}


const forArr = (arr, isExpand) => {
  arr.forEach((i) => {
    theTableRef.value.toggleRowExpansion(i, isExpand);
    if (i.children) {
      forArr(i.children, isExpand);
    }
  });
}
const expandAll = () => {
  // 默认展开全部的话，首次加载需要在$nextTick下进行
  forArr(dataOfTable.value, true);
}
const collapseAll = () => {
  forArr(dataOfTable.value, false);
}



// ======================================================
//                      处理事件
// ======================================================
/* 转树形数据 */
const getOptionData = (list) => {
  let cloneData = getNewObj(list); // 对源数据深度克隆
  return cloneData.filter((father) => {
    // 循环所有项，并添加children属性
    let branchArr = cloneData.filter(
      (child) => father.id == child.parentId
    ); // 返回每一项的子级数组
    branchArr.length > 0 ? (father.children = branchArr) : ""; //给父级添加一个children属性，并赋值
    return father.parentId == 0; //返回第一层
  });
}
const loadData = () => {
  let params = Object.assign({}, queryParam.value);
  EsAjax.post(ApiUrls.resourceTreegrid, { params }).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data + res.data.msg);
      return;
    }
    var oneList = [];
    var twoList = [];
    //组装父结点
    var csd = [];
    for (var dd = 0; dd < res.data.data.length; dd++) {
      var itemdd = res.data.data[dd];

      if (itemdd.Parent == null || itemdd.Parent.Id == 0) {
        csd.push({
          parentId: 0,
          id: itemdd.Id,
          name: itemdd.Name,
          value: itemdd.Id,
          label: itemdd.Name
        });
      } else {
        csd.push({
          parentId: itemdd.Parent.Id,
          id: itemdd.Id,
          name: itemdd.Name,
          value: itemdd.Id,
          label: itemdd.Name,
        });
      }
    }
    csd.unshift({ id: -1, name: "无", parentId: 0, value: -1, label: "无" });
    treeOption.value = getOptionData(csd)
    //组装tree table
    for (var i = 0; i < res.data.data.length; i++) {
      var item = res.data.data[i];
      if (item.Parent == null || item.Parent.Id == 0) {
        oneList.push(item);
      } else {
        twoList.push(item);
      }
    }
    var oneIdList = [];
    for (var ii = 0; ii < oneList.length; ii++) {
      oneIdList.push(oneList[ii].Id);
    }

    var realTwoList = [];
    var realThreeList = [];
    for (var j = 0; j < twoList.length; j++) {
      var item = twoList[j];
      if (oneIdList.indexOf(item.Parent.Id) != "-1") {
        realTwoList.push(twoList[j]);
      } else {
        realThreeList.push(twoList[j]);
      }
    }

    var dataList = [];
    for (var i = 0; i < oneList.length; i++) {
      var item = oneList[i];
      if (item.LinkUrl == "/home/index") {
        var objs = {
          id: item.Id,
          path: "/",
          component: "Layout",
          redirect: "index",
          label: item.Name,
          name: item.Name,
          Rtype: item.Rtype,
          Seq: item.Seq,
          Icon: item.Icon,
          FileName: item.FileName,
          // alwaysShow: true,
          children: [],
        };
      } else {
        var objs = {
          id: item.Id,
          path: item.Path,
          component: "Layout",
          redirect: "noRedirect",
          Rtype: item.Rtype,
          label: item.Name,
          Seq: item.Seq,
          name: item.Name,
          Icon: item.Icon,
          FileName: item.FileName,
          // name: item.Name,
          meta: { title: item.Name, icon: "cloud" },
          alwaysShow: true,
          children: [],
        };
      }
      dataList.push(objs);
    }

    var lastTwoList = [];
    for (var i = 0; i < realTwoList.length; i++) {
      var item = realTwoList[i];
      var objs = {
        parentId: item.Parent.Id,
        id: item.Id,
        path: item.Path,
        component: "EmptyLayout",
        redirect: "noRedirect",
        Rtype: item.Rtype,
        label: item.Name,
        Seq: item.Seq,
        Icon: item.Icon,
        name: item.Name,
        FileName: item.FileName,
        mete: {
          title: item.Name,
          permissions: ["admin"],
        },
        children: [],
      };
      lastTwoList.push(objs);
    }

    for (var i = 0; i < realThreeList.length; i++) {
      var item = realThreeList[i];
      lastTwoList.forEach((items) => {
        if (items.id == item.Parent.Id) {
          return items.children.push({
            meta: { title: item.Name },
            id: item.Id,
            label: item.Name,
            Seq: item.Seq,
            name: item.Name,
            Rtype: item.Rtype,
            Icon: item.Icon,
            FileName: item.FileName,
            parentId: item.Parent.Id,
            path: item.Path,
            children: [],
          });
        }
      });
    }

    for (var i = 0; i < lastTwoList.length; i++) {
      var item = lastTwoList[i];
      dataList.forEach((items) => {
        if (items.id == item.parentId) {
          return items.children.push(item);
        }
      });
    }
    dataOfTable.value = dataList
    // this.permissionsList = dataList;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}

loadData();
</script>